﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace RDIFramework.WebApp.Modules.handler
{
    using RDIFramework.BusinessEntity;
    using RDIFramework.ServiceAdapter;
    using RDIFramework.Utilities;
    using RDIFramework.WebCommon;

    /// <summary>
    /// ModuleAdminHandler 的摘要说明
    /// </summary>
    public class ModuleAdminHandler : IHttpHandler, IRequiresSessionState
    {
        // <summary> 
        /// 权限域编号(按权限管理范围来列出数据才可以，只能管理这个范围的数据)
        /// </summary>
        private string PermissionItemScopeCode = "Resource.ManagePermission";

        private string action
        {
            get
            {
                return RDIFramework.WebCommon.PublicMethod.GetString(getObj("action"));
            }
        }

        private object getObj(string key) { return RDIFramework.WebCommon.StringHelper.GetRequestObject(key); }


        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            switch (action)
            {
                case "Add":
                    AddModule(context);
                    break;
                case "Edit":
                    EditModule(context);
                    break;
                case "Delete":
                    DeleteModule(context);
                    break;
                case "GetModuleTree":
                    string treeData = this.GetJsonData();
                    treeData = treeData.Replace("Id", "id").Replace("FullName", "text").Replace("Expand", "state");//.Replace("\"state\":1", "\"state\":\"open\"").Replace("\"state\":0", "\"state\":\"closed\"");
                    context.Response.Write(treeData);
                    break;
                default:
                    string ss =  GetJsonData();
                    context.Response.Write(ss);
                    break;
            }
        }

        private PiModuleEntity GetPageModuleEntity(PiModuleEntity entity)
        {
            entity.Code = PublicMethod.GetString(getObj("Code"));
            entity.FullName = PublicMethod.GetString(getObj("FullName"));
            entity.Category = PublicMethod.GetString(getObj("vcategory"));
            entity.ParentId = PublicMethod.GetInt(getObj("vparentid"));
            entity.NavigateUrl = PublicMethod.GetString(getObj("NavigateUrl"));
            entity.IconCss = PublicMethod.GetString(getObj("IconCss"));
            entity.IconUrl = PublicMethod.GetString(getObj("IconUrl"));
            entity.AssemblyName = PublicMethod.GetString(getObj("AssemblyName"));
            entity.FormName = PublicMethod.GetString(getObj("FormName"));
            entity.Enabled = PublicMethod.GetString(getObj("Enabled")) == "on" ? 1 : 0;
            entity.IsPublic = PublicMethod.GetString(getObj("IsPublic")) == "on" ? 1 : 0;
            entity.Expand = PublicMethod.GetString(getObj("Expand")) == "on" ? 1 : 0;
            entity.AllowEdit = PublicMethod.GetString(getObj("AllowEdit")) == "on" ? 1 : 0;
            entity.AllowDelete = PublicMethod.GetString(getObj("Enabled")) == "on" ? 1 : 0;
            entity.Description = PublicMethod.GetString(getObj("Description"));
            return entity;
        }

        #region private void AddModule(HttpContext ctx) 增加模块（菜单）
        /// <summary>
        /// 增加模块（菜单）
        /// </summary>
        /// <param name="ctx"></param>
        private void AddModule(HttpContext ctx)
        {
            PiModuleEntity entity = new PiModuleEntity();
            UserInfo vUser = Utils.UserInfo;
            entity = this.GetPageModuleEntity(entity);
            entity.DeleteMark = 0;
            if (vUser != null)
            {
                entity.CreateBy = vUser.RealName;
                entity.CreateUserId = vUser.Id;
            }
            string statusCode = string.Empty;
            string statusMessage = string.Empty;
            try
            {
                RDIFrameworkService.Instance.ModuleService.Add(vUser, entity, out statusCode, out statusMessage);

                if (statusCode == StatusCode.OKAdd.ToString())
                {
                    ctx.Response.Write(new JsonMessage { Success = true, Data = "1", Message = statusMessage }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = statusMessage }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = statusMessage + ex.Message}.ToString());
            }
        }
        #endregion

        #region private void EditModule(HttpContext ctx) 编辑、修改模块（菜单）
        /// <summary>
        /// 编辑、修改模块（菜单）
        /// </summary>
        /// <param name="ctx"></param>
        private void EditModule(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string vId = PublicMethod.GetString(getObj("KeyId"));
            PiModuleEntity entity = RDIFrameworkService.Instance.ModuleService.GetEntity(vUser, vId);
            entity = this.GetPageModuleEntity(entity);
            if (vUser != null)
            {
                entity.ModifiedBy = vUser.RealName;
                entity.ModifyUserId = vUser.Id;
            }

            string statusCode = string.Empty;
            string statusMessage = string.Empty;
            try
            {
                RDIFrameworkService.Instance.ModuleService.Update(vUser, entity, out statusCode, out statusMessage);

                if (statusCode == StatusCode.OKUpdate.ToString())
                {
                    ctx.Response.Write(new JsonMessage { Success = true, Data = "1", Message = statusMessage }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = statusMessage }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = statusMessage + ex.Message}.ToString());
            }
        }
        #endregion

        #region private void DeleteModule(HttpContext ctx) 删除模块（菜单）
        /// <summary>
        /// 删除模块（菜单）
        /// </summary>
        /// <param name="ctx"></param>
        private void DeleteModule(HttpContext ctx)
        {
            string vId = PublicMethod.GetString(getObj("KeyId"));
            UserInfo vUser = Utils.UserInfo;

            int successFlag = 0;
            try
            {
                int returnValue = RDIFrameworkService.Instance.ModuleService.SetDeleted(Utils.UserInfo, new string[] { vId });

                if (returnValue > 0)
                {
                    successFlag = 1;
                    ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG0013 }.ToString());
                }
                else
                {
                    ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG3020 }.ToString());
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = RDIFrameworkMessage.MSG3020 + ex.Message }.ToString());
            } 
        }
        #endregion

        #region 得到数据
        private string GetJsonData()
        {
            List<PiModuleEntity> list = new List<PiModuleEntity>();

            foreach (DataRow drow in GetModuleScope(this.PermissionItemScopeCode).Rows)
            {
                list.Add(new PiModuleEntity(drow));
            }

            return "[" + GroupJSONdata(list, null) + "]";
        }

        private List<PiModuleEntity> GetGroups(List<PiModuleEntity> groups, int? parentid)
        {
            return groups.FindAll(delegate(PiModuleEntity gm) { return gm.ParentId == parentid; });
        }

        private string GroupJSONdata(List<PiModuleEntity> groups, int? parentId)
        {
            StringBuilder sb = new StringBuilder();
            List<PiModuleEntity> list = GetGroups(groups, parentId);
            string json = "";
            foreach (PiModuleEntity gm in list)
            {

                //json = JSONhelper.ToJson(gm);
                json = RDIFramework.Utilities.JsonHelper.ObjectToJSON(gm);
                json = json.TrimEnd('}');
                sb.Append(json);
                sb.Append(",");
                sb.Append("\"children\":[");
                sb.Append(GroupJSONdata(groups, gm.Id.Value));
                sb.Append("]},");
            }

            return sb.ToString().TrimEnd(',');
        }

        /// <summary>
        /// 获取模块菜单限域数据
        /// </summary>
        private DataTable GetModuleScope(string permissionItemScopeCode)
        {
            UserInfo vUser = Utils.UserInfo;
            // 获取部门数据
            if ((vUser.IsAdministrator) || (String.IsNullOrEmpty(permissionItemScopeCode) || (!SystemInfo.EnableUserAuthorizationScope)))
            {
                DataTable dtModule = RDIFrameworkService.Instance.ModuleService.GetDT(vUser);                
                // 这里需要只把有效的模块显示出来
                // BusinessLogic.SetFilter(dtModule, PiModuleTable.FieldEnabled, "1");
                // 未被打上删除标标志的
                // BusinessLogic.SetFilter(dtModule, PiModuleTable.FieldDeleteMark, "0");
                return dtModule;
            }
            else
            {
                DataTable dataTable = RDIFrameworkService.Instance.PermissionService.GetModuleDTByPermissionScope(vUser, vUser.Id, permissionItemScopeCode);               
                //BasePageLogic.CheckTreeParentId(dataTable, PiModuleTable.FieldId, PiModuleTable.FieldParentId);
                return dataTable;
            }
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}